package com.atguigu.edu.realtime.app.dws.traffic;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.bean.TrafficIsNewPageViewBean;
import com.atguigu.edu.realtime.bean.TrafficSourcePageViewBean;
import com.atguigu.edu.realtime.common.KafkaTopicConfig;
import com.atguigu.edu.realtime.sink.MyDorisSink;
import com.atguigu.edu.realtime.util.DateFormatUtil;
import com.atguigu.edu.realtime.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @ClassName: DwsTrafficIsNewPageViewWindow
 * @Description: TODO 流量域访客类别页面粒度各窗口汇总表
 * @Author: zhaoxunfeng
 * @Date: 2022-09-01 13:36
 * @Version: 1.0.0
 */
public class DwsTrafficIsNewPageViewWindow {
    public static void main(String[] args) {
        //TODO 1、环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(3);

        //TODO 2、读取 Kafka dwd_traffic_page_log 主题的数据并将其转换成对应的流
        String groupId = "DwsTrafficIsNewPageViewWindow";
        DataStreamSource<String> kafkaDS_1 = env.addSource(KafkaUtil.getKafkaConsumer(KafkaTopicConfig.DWD_TRAFFIC_PAGE_LOG_TOPIC, groupId));

        //TODO 3、将页面日志流中的数据封装成为 TrafficIsNewPageViewBean 对象
        SingleOutputStreamOperator<TrafficIsNewPageViewBean> pageDS = kafkaDS_1
                .map(JSONObject::parseObject)
                .keyBy(json -> json.getJSONObject("common").getString("sid"))
                .process(new KeyedProcessFunction<String, JSONObject, TrafficIsNewPageViewBean>() {

                    private ValueState<String> lastSessionId;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        lastSessionId = getRuntimeContext()
                                .getState(new ValueStateDescriptor<String>("last_session_id", String.class));
                    }

                    @Override
                    public void processElement(JSONObject json,
                                               Context ctx,
                                               Collector<TrafficIsNewPageViewBean> out) throws Exception {
                        JSONObject common = json.getJSONObject("common");
                        String isNew = common.getString("is_new");
                        JSONObject page = json.getJSONObject("page");
                        Long ts = json.getLong("ts");
                        Long duringTime = page.getLong("during_time");
                        Long pageCount = 1L;
                        Long sessionCount = 0L;

                        if (lastSessionId.value() == null) {
                            sessionCount = 1L;
                            lastSessionId.update(common.getString("sid"));
                        }
                        TrafficIsNewPageViewBean bean = TrafficIsNewPageViewBean
                                .builder()
                                .isNew(isNew)
                                .ts(ts)
                                .duringTime_sum(duringTime)
                                .page_count(pageCount)
                                .session_count(sessionCount)
                                .build();

                        out.collect(bean);
                    }
                });

        //TODO 4、读取kafka中独立访客数主题的数据,并创建对应的流
        DataStreamSource<String> kafkaDS_2 = env.addSource(KafkaUtil.getKafkaConsumer(KafkaTopicConfig.DWD_TRAFFIC_UNIQUE_VISITOR_DETAIL_TOPIC, groupId));

        //TODO 5、将独立访客流中的数据封装成为 TrafficIsNewPageViewBean 对象
        SingleOutputStreamOperator<TrafficIsNewPageViewBean> uvDS = kafkaDS_2.map(
                new RichMapFunction<String, TrafficIsNewPageViewBean>() {
                    @Override
                    public TrafficIsNewPageViewBean map(String value) throws Exception {
                        JSONObject json = JSONObject.parseObject(value);
                        String isNew = json.getJSONObject("common").getString("is_new");
                        Long ts = json.getLong("ts");

                        return TrafficIsNewPageViewBean.builder().isNew(isNew).uv_count(1L).ts(ts).build();
                    }
                });

        //TODO 6、读取kafka中 用户跳出 的数据,并创建对应的流
        DataStreamSource<String> kafkaDS_03 = env.addSource(KafkaUtil.getKafkaConsumer(KafkaTopicConfig.DWD_TRAFFIC_JUMP_DETAIL_TOPIC, groupId));

        //TODO 7、将用户跳出流中的数据封装成为 TrafficSourcePageViewBean 对象
        SingleOutputStreamOperator<TrafficIsNewPageViewBean> jumpDS = kafkaDS_03
                .map(new RichMapFunction<String, TrafficIsNewPageViewBean>() {
                    @Override
                    public TrafficIsNewPageViewBean map(String value) throws Exception {
                        JSONObject json = JSONObject.parseObject(value);
                        String isNew = json.getString("isNew");
                        Long ts = json.getLong("ts") * 1000L;

                        return TrafficIsNewPageViewBean.builder().isNew(isNew).jump_count(1L).ts(ts).build();
                    }
                });

        //TODO 8、将三个流进行合并
        DataStream<TrafficIsNewPageViewBean> unionDS = pageDS.union(uvDS, jumpDS);

        //TODO 9、分配时间戳并按照 来源进行分区
        KeyedStream<TrafficIsNewPageViewBean, String> keyedStream = unionDS.assignTimestampsAndWatermarks(WatermarkStrategy
                .<TrafficIsNewPageViewBean>forBoundedOutOfOrderness(Duration.ofSeconds(10))
                .withTimestampAssigner((bean, ts) -> bean.getTs())
        ).keyBy(TrafficIsNewPageViewBean::getIsNew);

        //TODO 10、开窗聚合计算
        SingleOutputStreamOperator<TrafficIsNewPageViewBean> result = keyedStream
                .window(TumblingProcessingTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<TrafficIsNewPageViewBean>() {
                    @Override
                    public TrafficIsNewPageViewBean reduce(TrafficIsNewPageViewBean value1, TrafficIsNewPageViewBean value2) throws Exception {
                        value1.setPage_count(value1.getPage_count() + value2.getPage_count());
                        value1.setDuringTime_sum(value1.getDuringTime_sum() + value2.getDuringTime_sum());
                        value1.setUv_count(value1.getUv_count() + value2.getUv_count());
                        value1.setJump_count(value1.getJump_count() + value2.getJump_count());
                        value1.setSession_count(value1.getSession_count() + value2.getSession_count());
                        return value1;
                    }
                }, new ProcessWindowFunction<TrafficIsNewPageViewBean, TrafficIsNewPageViewBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context context,
                                        Iterable<TrafficIsNewPageViewBean> elements,
                                        Collector<TrafficIsNewPageViewBean> out) throws Exception {

                        TrafficIsNewPageViewBean result = elements.iterator().next();
                        String stt = DateFormatUtil.toDateTimeString(context.window().getStart());
                        String edt = DateFormatUtil.toDateTimeString(context.window().getEnd());
                        result.setIsNew(key);
                        result.setStt(stt);
                        result.setEdt(edt);
                        result.setTs(System.currentTimeMillis());
                        result.setCur_date(DateFormatUtil.toPartitionDate(context.window().getStart()));
                        out.collect(result);
                    }
                });

        //TODO 11、将得到的结果写出到对应数据库中
        result.addSink(new MyDorisSink<TrafficIsNewPageViewBean>("dws_traffic_is_new_page_view_window", "cur_date"));

        //TODO 12、开始执行程序
        try {
            env.execute();
        } catch (
                Exception e) {
            throw new RuntimeException(e);
        }
    }
}
